package io.kiki.sba.registry.common.model;

import io.kiki.sba.registry.concurrent.ThreadLocalStringBuilder;
import lombok.Getter;
import lombok.Setter;

import java.io.Serializable;

@Setter
@Getter
public class TraceTimes implements Serializable {
    private long createTs;
    private int dataChangeType;
    private long firstDataChange;
    private long datumNotifyCreate;
    private long datumNotifySend;

    private long triggerSession;

    public TraceTimes() {
        createTs = System.currentTimeMillis();
    }


    public TraceTimes copy() {
        TraceTimes times = new TraceTimes();
        times.createTs = createTs;
        times.dataChangeType = dataChangeType;
        times.firstDataChange = firstDataChange;
        times.datumNotifyCreate = datumNotifyCreate;
        times.datumNotifySend = datumNotifySend;
        times.triggerSession = triggerSession;
        return times;
    }

    public boolean beforeThan(TraceTimes times) {
        return this.createTs < times.createTs;
    }

    private long delay(long from, long to) {
        if (from == 0 || to == 0) {
            return 0;
        }
        return to - from;
    }

    public String format(long endTs) {
        StringBuilder sb = ThreadLocalStringBuilder.get();
        sb.append("{");
        sb.append("chgType=").append(dataChangeType).append(",");
        sb.append("dataDelay=").append(delay(firstDataChange, endTs)).append(",");
        sb.append(delay(datumNotifyCreate, endTs)).append(",");
        sb.append(delay(datumNotifySend, endTs)).append(",");
        sb.append(delay(triggerSession, endTs));
        sb.append("}");
        return sb.toString();
    }


}
